8<template>
  <div class="container">
    <div class="app-container">
      <!-- 角色管理 -->
      <el-row class="btn_container">
        <el-button size="mini" type="primary" @click="showDialog = true">添加角色</el-button>
      </el-row>
      <!-- 表格组件 -->
      <el-table v-loading="loading" :data="list">
        <!-- 列信息 -->
        <el-table-column align="center" label="角色" prop="name">
          <template v-slot="{row}">
            <span v-if="!row.isEdit">{{ row.name }}</span>
            <el-input v-else v-model="row.rowEdit.name" size="mini" placeholder="请输入角色名称" />
          </template>
        </el-table-column>
        <el-table-column align="center" label="启用" prop="state">
          <template v-slot="{ row }">
            <template v-if="!row.isEdit">
              {{ row.state === 1 ? '已启用' : '未启用' }}
            </template>
            <el-switch v-else v-model="row.rowEdit.state" size="mini" :active-value="1" :inactive-value="0" />
          </template>
        </el-table-column>
        <el-table-column align="center" label="描述" prop="description">
          <template v-slot="{row}">
            <span v-if="!row.isEdit">{{ row.description }}</span>
            <el-input v-else v-model="row.rowEdit.description" size="mini" type="textarea" placeholder="请输入角色描述" :rows="3" />
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作">
          <template v-slot="{row}">
            <template v-if="!row.isEdit">
              <el-button size="mini" type="text" @click="btnPermission(row.id)">分配权限</el-button>
              <el-button size="mini" type="text" @click="btnEditRow(row)">编辑</el-button>
              <el-popconfirm
                title="确定删除该角色吗？"
                @onConfirm="confirmDel(row.id)"
              >
                <template #reference>
                  <el-button style="margin-left: 10px" size="mini" type="text">删除</el-button>
                </template>
              </el-popconfirm>
            </template>
            <template v-else>
              <el-button size="mini" type="primary" @click="btnEditOk(row)">确定</el-button>
              <el-button size="mini" @click="row.isEdit = false">取消</el-button>
            </template>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页组件 -->
      <el-row style="height:80px" type="flex" justify="end" align="middle">
        <el-pagination
          layout="prev, pager, next, jumper, total"
          :total="pageParams.total"
          :page-size="pageParams.pagesize"
          :current-page="pageParams.page"
          @current-change="changePage"
        />
        <!-- 1 -> 2 -->
      </el-row>
    </div>
    <el-dialog width="500px" title="新增角色" :visible.sync="showDialog" @close="btnCancel">
      <el-form ref="addRole" label-width="80px" :model="addForm" :rules="addRules">
        <el-form-item prop="name" label="角色名称">
          <el-input v-model="addForm.name" size="mini" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item prop="state" label="启用">
          <el-switch v-model="addForm.state" :inactive-value="0" :active-value="1" size="mini" />
        </el-form-item>
        <el-form-item prop="description" label="角色描述">
          <el-input v-model="addForm.description" size="mini" placeholder="请输入角色描述" />
        </el-form-item>
        <el-row type="flex" justify="center">
          <el-button size="mini" @click="btnCancel">取消</el-button>
          <el-button size="mini" type="primary" @click="btnOK">确定</el-button>
        </el-row>
      </el-form>
    </el-dialog>
    <!-- 放置权限弹层 -->
    <el-dialog
      width="500px"
      title="分配权限"
      :visible.sync="showAssignDialog"
      @close="showAssignDialog = false"
    >
      <el-tree
        ref="permissionTree"
        :data="permissionTreeData"
        check-strictly
        show-checkbox
        node-key="id"
        default-expand-all
        :props="{
          label: 'name',
          children: 'children'
        }"
      />
      <el-row slot="footer" type="flex" justify="center">
        <el-col :span="6">
          <el-button type="primary" size="mini" @click="btnAssignRole">确定</el-button>
          <el-button size="mini" @click="showAssignDialog = false">取消</el-button>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>
<script>
import { addRoleAPI, getRoleListAPI, upDateRoleAPI, delRoleAPI, getPermissionListAPI, getRoleDetailAPI, assignRoleAPI } from '@/api'
import { transListToTreeDate } from '@/utils'

export default {
  name: 'Role',
  data() {
    return {
      isEdit: false,
      loading: false,
      list: [], // 据驱动视图 对数据进行劫持 监听get/set => 监听到变化 => 反应到UI上
      pageParams: {
        total: 0,
        page: 1, // 默认请求第一页
        pagesize: 5 // 每页5条
      },
      showDialog: false,
      addRules: {
        name: [{ required: true, message: '角色名称不能为空' }],
        description: [{ required: true, message: '角色描述不能为空' }]
      },
      addForm: {
        name: '',
        description: '',
        state: 0

      },
      showPermissionDialog: false,
      permissionData: [],
      currentRoleId: null, // 记录点击角色id
      permissionTreeData: [], // 用来展示权限的数据
      showAssignDialog: false
    }
  },
  created() {
    this.getRoleList()
  },
  methods: {
    async btnAssignRole() {
      // 获取当前树组件选中的key
      await assignRoleAPI({ id: this.currentRoleId, permIds: this.$refs.permissionTree.getCheckedKeys() })
      this.showAssignDialog = false
      this.$message.success('分配权限成功')
    },
    async btnOK() {
      await this.$refs.addRole.validate()
      await addRoleAPI(this.addForm)
      this.$message.success('新增角色成功')
      this.btnCancel()
      this.getRoleList() // 重新获取数据
    },
    btnCancel() {
      this.showDialog = false
      this.$refs.addRole.resetFields()
    },
    async getRoleList() {
      this.loading = true
      const { rows, total } = await getRoleListAPI(this.pageParams)
      this.list = rows
      // 拿到了当前页的数据
      // 每个数据上添加一个是否编辑的状态
      this.list.forEach(item => {
        // ✳️反面参考 --  item.isEdit = false I/非编辑状态//此时没有数据劫持
        // 直接添上属性是非响应式的
        // 非响应式数据=>响应式的
        this.$set(item, 'isEdit', false) // 添加对于IsEdit的响应式数据劫持 -- 驱动UI的更新
        // 取消还原编辑数据
        this.$set(item, 'rowEdit', {
          name: item.name,
          state: item.state,
          description: item.description
        })
        // 确定更新编辑数据
        // this.$set
      })
      this.pageParams.total = total
      this.loading = false
    },
    // 页码改变事件
    changePage(newPage) {
      this.pageParams.page = newPage // 赋值新页码
      this.getRoleList()
    },
    btnEditRow(row) {
      row.isEdit = true // 改变行的编辑状态
      // 缓存编辑数据
      row.rowEdit.name = row.name
      row.rowEdit.state = row.state
      row.rowEdit.description = row.description
    },
    async btnEditOk(row) {
      if (row.rowEdit.name && row.rowEdit.description) {
        await upDateRoleAPI({ ...row.rowEdit, id: row.id })
        this.$message.success('角色更新成功')
        Object.assign(row, {
          ...row.rowEdit,
          isEdit: false
        })
        // this.isEdit = false
      } else {
        this.$message.warning('角色和描述不能为空')
      }
    },
    async  confirmDel(id) {
      await delRoleAPI(id)
      this.$message.success('删除成功')
      // 下午好好敲一下
      if (this.list.length === 1) this.pageParams.page-- // 页码-1
      this.getRoleList()
    },
    async btnPermission(id) {
      this.currentRoleId = id
      try {
        // 获取权限树数据
        const res = await getPermissionListAPI()
        this.permissionTreeData = transListToTreeDate(res, 0) // 列表转化树形

        // 获取角色详情
        const roleDetail = await getRoleDetailAPI(id)
        const permIds = roleDetail.permIds || []

        // 显示弹窗并设置选中状态
        this.showAssignDialog = true // 渲染是异步的
        this.$nextTick(() => {
          this.$refs.permissionTree.setCheckedKeys(permIds) // 设置选中的key
        })
      } catch (error) {
        this.$message.error('获取权限数据失败')
      }
    }
  }
}
</script>
<style scoped>
.btn_container {
  padding: 10px 20px;
}
</style>
